import SignRecord from '../model/SignRecord'
import { getJWTPayload } from '../common/Utils'
import User from '../model/User'
import moment from 'moment'
import send from '@/config/MailConfig'
import { v4 as uuid } from 'uuid'
import jwt from 'jsonwebtoken'
import { setValue, getValue } from '@/config/RedisConfig'
import config from '@/config'
import bcypt from 'bcryptjs'
import qs from 'qs'
import List from '@/model/List'
import Collect from '@/model/collect'
import Comments from '@/model/Comments'

class UserController {
  async userSign(ctx) {
    const obj = await getJWTPayload(ctx.header.authorization)
    const user = await User.findByID(obj._id)
    //取用户id
    //查用户上一次记录
    const record = await SignRecord.findByUid(obj._id)
    let newRecord = {}
    let result = {}
    if (record !== null) {
      //有历史签到
      //判断用户上次时间和当前时间是否相同
      if (
        moment(record.created).format('YYYY-MM-DD') ===
        moment().format('YYYY-MM-DD')
      ) {
        ctx.body = {
          code: 500,
          msg: '用户已经签到了',
          favs: user.favs,
          count: user.count,
          lastSign: record.lastSign,
        }
        return
      } else {
        //有签到记录不与今天相同
        let count = user.count
        let fav = 0
        //判断签到时间
        if (
          moment(record.created).format('YYYY-MM-DD') ===
          moment().subtract(1, 'days').format('YYYY-MM-DD')
        ) {
          count += 1
          if (count < 5) {
            fav = 5
          } else if (count >= 5 && count < 15) {
            fav = 10
          } else if (count >= 15 && count < 30) {
            fav = 15
          } else if (count >= 30 && count < 100) {
            fav = 20
          } else if (count >= 100 && count < 365) {
            fav = 30
          } else if (count >= 365) {
            fav = 50
          }
          await User.updateOne(
            { _id: obj._id },
            {
              $inc: { fav: fav, count: 1 },
            }
          )
          result = {
            favs: user.favs + fav,
            count: user.count + 1,
          }
        } else {
          //中断
          fav = 5
          await User.updateOne(
            { _id: obj._id },
            {
              $set: { count: 1 },
              $inc: { favs: fav },
            }
          )
          result = {
            favs: user.favs + fav,
            count: 1,
          }
        }
        //更新签到记录
        newRecord = new SignRecord({
          uid: obj._id,
          favs: fav,
        })
        await newRecord.save()
      }
    } else {
      //无签到数据
      await User.updateOne(
        {
          _id: obj._id,
        },
        {
          $set: { count: 1 },
          $inc: { favs: 5 },
        }
      )
      //保存签到记录
      newRecord = new SignRecord({
        uid: obj._id,
        favs: 5,
      })
      await newRecord.save()
      result = {
        fav: user.favs + 5,
        count: 1,
      }
    }
    //判断签到逻辑
    ctx.body = {
      code: 200,
      msg: '请求成功',
      ...result,
      lastSign: newRecord.created,
    }
  }
  //更新基本信息
  async updateUserInfo(ctx) {
    const { body } = ctx.request
    // let Body = JSON.parse(body)
    const obj = await getJWTPayload(ctx.header.authorization)
    const user = await User.findOne({ _id: obj._id })
    let msg = ''
    if (body.username && body.username !== user.username) {
      //发送邮件
      //判断用户的新邮箱是否有人已经注册
      const tmpUser = User.findOne({ username: body.username })
      if (tmpUser && tmpUser.password) {
        ctx.body = {
          code: 501,
          msg: '用户邮箱已经注册',
        }
        return
      }
      const key = uuid()
      setValue(
        key,
        jwt.sign({ _id: obj._id }, config.JWT_SECRET, {
          expiresIn: '30m',
        })
      )
      const result = await send({
        type: 'email',
        data: {
          key: key,
          username: body.username,
        },
        code: '',
        expire: moment().add(30, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        email: user.username,
        user: user.name,
      })
      msg = '更新基本信息成功，账号修改需要进行邮件确认，注意查收邮件'
    }
    const arr = ['password', 'mobile', 'username']
    arr.map((item) => {
      delete body[item]
    })
    const result = await User.updateOne({ _id: obj._id }, body)
    if (result.modifiedCount === 1 && result.matchedCount === 1) {
      ctx.body = {
        code: 200,
        msg: msg === '' ? '更新成功' : msg,
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '更新失败',
      }
    }
  }
  //更新用户名
  async updateUsername(ctx) {
    const body = ctx.query
    if (body.key) {
      const token = await getValue(body.key)
      const obj = await getJWTPayload('Bearer ' + token)
      await User.updateOne(
        { _id: obj._id },
        {
          username: body.username,
        }
      )
      ctx.body = {
        code: 200,
        msg: '更新用户名成功',
      }
    }
  }
  //更改密码
  async updateWord(ctx) {
    const { body } = ctx.request
    const password = body.password
    const obj = await getJWTPayload(ctx.header.authorization)
    let user = await User.findOne({ _id: obj._id })
    let checkUserPasswd = false
    if (await bcypt.compare(body.nowpassword, user.password)) {
      checkUserPasswd = true
    }
    if (checkUserPasswd) {
      const newpassword = await bcypt.hash(body.password, 5)
      const result = await User.updateOne(
        { _id: obj._id },
        { $set: { password: newpassword } }
      )
      ctx.body = {
        code: 200,
        msg: '更新密码成功',
      }
    } else {
      ctx.body = {
        code: 404,
        msg: '密码错误',
      }
    }
  }
  //获取用户文章
  async postList(ctx) {
    const body = qs.parse(ctx.request.query)
    const obj = await getJWTPayload(ctx.header.authorization)
    if (obj._id !== 'undefined') {
      const list = await List.find({
        uid: body.uid,
      })
      ctx.body = {
        code: 200,
        msg: '获取文章列表成功',
        data: list,
      }
    }
  }
  //删除文章
  async setdel(ctx) {
    const body = qs.parse(ctx.request.query)
    const obj = await getJWTPayload(ctx.header.authorization)
    if (typeof obj !== 'undefined' && obj._id !== '') {
      const post = await List.findOne({ _id: body.tid })
      if (post !== 'undefined' && post.isEnd !== '1') {
        const list = await List.deleteOne({ _id: body.tid })
        if (list.deletedCount === 1) {
          ctx.body = {
            code: 200,
            msg: '删除文章成功',
          }
        } else {
          ctx.body = {
            code: 500,
            msg: '删除文章失败',
          }
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '帖子已经结贴无法删除',
        }
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '用户未登陆,或无权限',
      }
    }
  }
  //获取用户收藏
  async getcollect(ctx) {
    const body = qs.parse(ctx.request.query)
    const obj = await getJWTPayload(ctx.header.authorization)
    if (obj._id !== 'undefined') {
      const collect = await Collect.find({
        uid: body.uid,
      })
      ctx.body = {
        code: 200,
        msg: '获取文章列表收藏',
        data: collect,
      }
    }
  }
  //获取用户中心
  async getInfor(ctx) {
    const body = qs.parse(ctx.request.query)
    const obj = await getJWTPayload(ctx.header.authorization)
    const uid = body.uid || obj._id
    const user = await User.findByID(uid)
    //去取用户签到记录 >todady 0点
    // user = user.toJSON()
    // let date = moment().format('YYYY-MM-DD')
    // let result = await SignRecord.findOne(
    //   { uid: uid },
    //   {
    //     $get: date + '00:00:00',
    //   }
    // )
    // if (result.uid) {
    //   user.isSign = true
    // } else {
    //   user.isSign = false
    // }
    ctx.body = {
      code: 200,
      data: user,
      msg: '查询成功',
    }
  }
  async getMsg(ctx) {
    const body = qs.parse(ctx.request.query)
    const page = body.page ? body.page : 0
    const limit = body.limit ? parseInt(body.limit) : 0
    //方法嵌套查询 -》aggregate
    const obj = await getJWTPayload(ctx.header.authorization)
    const num = await Comments.getTotal(obj._id)
    const result = await Comments.getMsgList(obj._id, page, limit)
    ctx.body = {
      code: 200,
      data: result,
      msg: '查询成功',
      total: num,
    }
    //通过冗余换时间
    // console.log(body)
  }
  async setMsg(ctx) {
    const body = qs.parse(ctx.request.query)
    if (body.id) {
      const result = await Comments.updateOne({ _id: body.id }, { isRead: '1' })
      if (result.modifiedCount === 1) {
        ctx.body = {
          code: 200,
          data: result,
          msg: '设置成功',
        }
      }
    } else {
      const obj = await getJWTPayload(ctx.header.authorization)
      if (obj !== 'undefined' && obj._id !== '') {
        const result = await Comments.updateMany(
          { uid: obj._id },
          { isRead: '1' }
        )
        if (result.modifiedCount === 1) {
          ctx.body = {
            code: 200,
            data: result,
            msg: '设置全部成功',
          }
        }
      }
    }
  }
  async getUserInfor(ctx) {
    const body = qs.parse(ctx.request.query)
    let result = await User.findByID({ _id: body.uid })
    let list = await List.find({ uid: body.uid })
    let comments = await Comments.find({ uid: body.uid })
    ctx.body = {
      code: 200,
      data: result,
      list: list,
      comments: comments,
    }
  }
}

export default new UserController()
